import 'package:flutter/cupertino.dart';

import '../../../constants.dart';
import '../../../main.dart' hide Diary;
import '../../../router/routes.dart';
import '../../../util/db_util.dart';
import '../../../util/eventbus_util.dart';
import '../widget/diary_list_widget.dart';

class ExploreAllPage extends StatefulWidget {
  const ExploreAllPage({Key? key}) : super(key: key);

  @override
  State<ExploreAllPage> createState() => _ExploreAllPageState();
}

class _ExploreAllPageState extends State<ExploreAllPage> {
  var saveDiaryDoneListener;
  List<Map<String, Object?>> allDiaryRow = [];
  List<Diary> allDiary = [];

  // 添加新日记按钮
  Widget addNewDiaryButton() {
    return Positioned(
      right: 20,
      bottom: 20,
      child: CupertinoButton(
        child: Container(
          width: 60,
          height: 60,
          decoration: BoxDecoration(
            color: Consts.themeColor,
            borderRadius: const BorderRadius.all(Radius.circular(80)),
            border: Border.all(width: 0, style: BorderStyle.none),
            boxShadow: const [
              BoxShadow(
                  color: CupertinoColors.systemBlue,
                  offset: Offset(5.0, 5.0),
                  blurRadius: 15.0,
                  spreadRadius: 0.1)
            ],
          ),
          child: const Icon(
            CupertinoIcons.add,
            color: CupertinoColors.white,
            size: 20,
          ),
        ),
        onPressed: () {
          router.navigateTo(context, "${Routes.writeDiaryPage}/-1");
        },
      ),
    );
  }

  // 载入所有日记
  void loadAllDiary() async {
    await DatabaseUtil.instance.openDb();
    allDiaryRow = await DatabaseUtil.instance.queryAll();
    allDiary.clear();
    if (allDiaryRow.isNotEmpty) {
      for (int i = 0; i < allDiaryRow.length; i++) {
        allDiary.add(Diary().fromMap(allDiaryRow[i]));
      }
    }
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    // 日记保存成功监听器
    saveDiaryDoneListener = eventBus.on<DiaryListChanged>().listen((event) {
      loadAllDiary();
    });
    loadAllDiary();
  }

  @override
  void dispose() {
    super.dispose();
    saveDiaryDoneListener.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        width: double.infinity,
        height: double.infinity,
        padding: const EdgeInsets.only(top: 5),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.cover,
            image: AssetImage('assets/image/bg.jpg'),
          ),
        ),
        child: Stack(children: [
          DiaryListWidget.diaryList(allDiary),
          addNewDiaryButton()
        ]),
      ),
    );
  }
}
